﻿$(document).ready(function() {
    $(".entry:odd").css("backgroundColor", "#f9f9f9");

    //intro animation
    $(".intro").hide().each(function() {
        $(this).slideDown(300);
    });

    //get listing of top ranked articles
    $.getJSON("/Articles/TopRanked?count=5",
        function(data) {
            var html = "";
            $.each(data, function(i, item) {
                var t = "<div style=\"width: 65%;\">" + (i + 1) + ") <a href=\"/Articles/Details/" + item.RecId + "_" + item.Title.replace(" ", "_", "g") + "\">" + item.Title + "</a></div>";
                var p = "<div class=\"right\" style=\"width: 35%;\"><img style=\"vertical-align: text-top;\" src=\"/Content/Images/level.png\" border=0 /> " + item.Points + " Point(s)</div>";
                html += p + t + "<div class=\"clear\">&nbsp;</div>";
            });
            $("#divPopularArticles").html(html);
        });

    //set order link color
    var viewAction = $("input[name='ViewAction']").val();
    if (viewAction != null && viewAction.indexOf("Popular") == -1) {
        //set selected class and disable further links on it
        $("a[rel='lnkMostRecent']").addClass("selected")
        .click(function(e) {
            e.preventDefault();
        });
    }
    else {
        //set selected class and disable further links on it
        $("a[rel='lnkMostPopular']").addClass("selected")
        .click(function(e) {
            e.preventDefault();
        });
    }

    //on details page we need all response types so make an ajax call to get em
    if (document.location.href.indexOf("/Details/") != -1) {
        detailsViewJs();
    }
});

//details page js
function detailsViewJs() {
    var responseTypes;
    $.getJSON("/Comments/Types",
        function(data) {
            responseTypes = data;
            $("a[rel^='lnkComment']").parent().show();
        });

        $("a[rel='lnkCloseComments']").click(function(e) {
            e.preventDefault();
            var target;
            if ($(this).data("hiding")) {
                target = $(this).parent().parent().nextAll();
                if ($(this).data("except"))
                    target.not(".commentlink").slideDown(300);
                else
                    target.not("div[id^='doComment-']").slideDown(300);
                $(this).data("hiding", false).data("except", false).html("close");
            }
            else {
                target = $(this).parent().parent().nextAll();
                //if user was writing a comment - try to rem whats visible - for toggle
                $(this).data("except", $("div[id^='doComment-']", target.parent()).is(":visible"));
                target.slideUp(300);
                $(this).data("hiding", true).html("open");
            }
        });

    //article details page js
    $("a[rel^='lnkComment']").click(function(e) {
        e.preventDefault();

        var id = $(this).attr("rel").split("-")[1];
        //create options list for response types
        var responseTypesOpts = "";
        if (responseTypes) {
            $.each(responseTypes, function(i, option) {
                responseTypesOpts += "<input type=\"radio\" name=\"rt-" + id + "\" value=\"" + option + "\" />" + option + " ";
            });
            responseTypesOpts = "<div>" + responseTypesOpts + "</div>";
        }
        var elem = $("#doComment-" + id);
        if (elem.length) {
            $(this).parent().hide();
            elem.show();
            $("input:radio[name='rt-" + id + "']").attr("checked", false);
            $("#ta-" + id).val("").attr("disabled", false).focus();
        }
        else {
            $(this).parent().hide().prev().after("<div id=\"doComment-" + id + "\">" + responseTypesOpts + "<div class=\"ta\"><textarea id=\"ta-" + id + "\"></textarea></div><div class=\"commentlink\"><a href=# rel=\"lnkPost-" + id + "\">Post Comment</a></div></div>");
            $("#ta-" + id).focus().autogrow();
        }
    }).parent().hide();

    //set event on the new post link (live event becoz these links will be created dynamically)
    $("a[rel^='lnkPost']").live('click', function(e) {
        e.preventDefault();
        var nameArr = $(this).attr("rel").split("-");
        var id = nameArr[1];
        var p;
        var _this = $(this);
        if (_this.data("processing"))
            return;
        else
            _this.data("processing", true);

        //check comment type - only for regular comments
        if (nameArr[0] == "lnkPost") {
            var ct = $("input[name='rt-" + id + "']:checked");
            //show or hide error
            p = $("input[name='rt-" + id + "']").parent();
            if (p.data("dispErr")) {
                if (ct.length)
                    p.data("dispErr", 0).children("span.error").remove();
            }
            else {
                if (!ct.length)
                    p.data("dispErr", 1).prepend("<span class=\"error\">Choose One ...</span>");
            }
        }

        //check comment
        if (nameArr[0] == "lnkPostReply")
            var c = $("#rta-" + id);
        else
            var c = $("#ta-" + id);
        //get comment content
        var ctext = $.trim(c.val());
        //show or hide error
        p = c.parent().next();
        if (p.data("dispErr")) {
            if (ctext.length)
                p.data("dispErr", 0).children("div.error").remove();
        }
        else {
            if (!ctext.length)
                p.data("dispErr", 1).prepend("<div class=\"error\">Write Something ...</div>");
        }

        //validate before attempting to save comment
        var validated = false;
        var urlParam = "";
        var dataParams = "";
        var isReply = false;
        if (nameArr[0] == "lnkPost") {
            var type = ct.val();
            if (type && ctext) {
                validated = true;
                urlParam = "/Comments/Add";
                dataParams = "id=" + id + "&type=" + type + "&content=" + escape(ctext);
            }
        }
        else if (nameArr[0] == "lnkPostReply") {
            if (ctext) {
                validated = true;
                urlParam = "/Replies/Add";
                dataParams = "id=" + id + "&content=" + escape(ctext);
                isReply = true;
            }
        }

        //save comment
        if (validated) {
            c.attr("disabled", true);
            $.ajax({
                type: "POST",
                url: urlParam,
                data: dataParams,
                dataType: "json",
                success: function(data) {
                    _this.data("processing", false);
                    if (!data.Status) { alert(data.Message); return; }
                    //comment
                    if (!isReply) {
                        //hide comment box area
                        $("#doComment-" + id).hide();
                        var rid = data.Message.split("-")[0];
                        var closeImg = "<img class=\"crbutton\" alt=\"delete\" title=\"delete\" rel=\"del-" + rid + "\" src=\"../../Content/Images/close.png\"/>";
                        var toneHtml = "";
                        if (type == 'Agree')
                            toneHtml = "<img alt=\"Thumbs Up\" src=\"../../Content/Images/thumbsup.gif\"/>";
                        else if (type == 'Disagree')
                            toneHtml = "<img alt=\"Thumbs Down\" src=\"../../Content/Images/thumbsdown.gif\"/>";
                        var msg = data.Message.split("-")[1];
                        //render html
                        $("a[rel='lnkComment-" + id + "']").parent().show().after("<div class=\"postedcomment\"><div>" + closeImg + msg + "</div><div>" + toneHtml + ctext + "</div></div>");
                    }
                    //reply
                    else {
                        //get reply id
                        var rid = data.Message.split("-")[0];
                        var closeImg = "<img class=\"crbutton\" alt=\"delete\" title=\"delete\" rel=\"delreply-" + rid + "\" src=\"../../Content/Images/close.png\"/>";
                        var msg = data.Message.split("-")[1];
                        //render reply html
                        $("#doReply-" + id).hide().after("<div class=\"postedreply\"><div>" + closeImg + "<div class=\"info\">" + msg + "</div></div><div>" + ctext + "</div></div>");
                    }
                },
                error: function(e, r, s) { alert(e + " - " + r + " - " + s); _this.data("processing", false); }
            });
        }
        else
            _this.data("processing", false);
    });

    //delete or reply comment button
    $(".crbutton").live('click', function(e) {
        var nameArr = $(this).attr("rel").split("-");
        var id = nameArr[1];
        var parent = $(this).parent().parent();
        var _this = $(this);
        if (_this.data("processing"))
            return;
        else
            _this.data("processing", true);
        //action
        if (nameArr[0] == "reply") {
            //show reply area
            var elem = $("#doReply-" + id);
            if (elem.length) {
                elem.show();
                $("#rta-" + id).val("").attr("disabled", false).focus();
            }
            else {
                parent.children(":nth-child(2)").after("<div id=\"doReply-" + id + "\"><div class=\"ta\"><textarea id=\"rta-" + id + "\"></textarea></div><div><a href=# rel=\"lnkPostReply-" + id + "\">Post Comment</a></div></div>");
                $("#rta-" + id).focus().autogrow();
            }
            _this.data("processing", false);
        }
        else {
            var urlParam = "";
            if (nameArr[0] == "del")
                urlParam = "/Comments/Delete";
            else
                urlParam = "/Replies/Delete";
            $.ajax({
                type: "POST",
                url: urlParam,
                data: "id=" + id,
                dataType: "json",
                success: function(data) {
                    _this.data("processing", false);
                    if (!data.Status) { alert(data.Message); return; }
                    //remove the comment
                    parent.remove();
                },
                error: function(e, r, s) { alert(e + " - " + r + " - " + s); _this.data("processing", false); }
            });
        }
    });
}

//http: //github.com/jaz303/jquery-grab-bag/blob/master/javascripts/jquery.autogrow-textarea.js
(function($){$.fn.autogrow=function(options){this.filter('textarea').each(function(){var $this=$(this),minHeight=$this.height(),lineHeight=$this.css('lineHeight');var shadow=$('<div></div>').css({position:'absolute',top:-10000,left:-10000,width:$(this).width()-parseInt($this.css('paddingLeft'))-parseInt($this.css('paddingRight')),fontSize:$this.css('fontSize'),fontFamily:$this.css('fontFamily'),lineHeight:$this.css('lineHeight'),resize:'none'}).appendTo(document.body);var update=function(){var times=function(string,number){for(var i=0,r='';i<number;i++)r+=string;return r};var val=this.value.replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/&/g,'&amp;').replace(/\n$/,'<br/>&nbsp;').replace(/\n/g,'<br/>').replace(/ {2,}/g,function(space){return times('&nbsp;',space.length-1)+' '});shadow.html(val);$(this).css('height',Math.max(shadow.height()+20,minHeight))};$(this).change(update).keyup(update).keydown(update);update.apply(this)});return this}})(jQuery);
